﻿#region Copyright
// Copyright (c) 2010, Kazi Manzur Rashid <kazimanzurrashid@gmail.com>.
// This source is subject to the Microsoft Public License. 
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. 
// All other rights reserved.
#endregion

namespace LiveWriter.Plugins.HighlightJS
{
    using System;
    using System.Globalization;
    using System.Windows.Forms;

    using WindowsLive.Writer.Api;

    [WriterPlugin("4B7CDFA8-4700-488f-92B6-2AEB814803F9", "HighlightJS", Description = "Code Snippet based upon HighlightJS(http://softwaremaniacs.org/soft/highlight/en/)", HasEditableOptions = true, PublisherUrl = Constants.Home)]
    [InsertableContentSourceAttribute("Insert Code", SidebarText = "Insert Code")]
    public class Plugin : SmartContentSource
    {
        public override void EditOptions(IWin32Window dialogOwner)
        {
            using (DefaultSetting form = new DefaultSetting(Options))
            {
                form.ShowDialog(dialogOwner);
            }
        }

        public override DialogResult CreateContent(IWin32Window dialogOwner, ISmartContent newContent)
        {
            newContent.Properties.Language(Options.Language());

            using (CodeEditor form = new CodeEditor { Properties = newContent.Properties })
            {
                return form.ShowDialog(dialogOwner);
            }
        }

        public override string GenerateEditorHtml(ISmartContent content, IPublishingContext publishingContext)
        {
            return GenerateHtml(content);
        }

        public override string GeneratePublishHtml(ISmartContent content, IPublishingContext publishingContext)
        {
            return GenerateHtml(content);
        }

        public override SmartContentEditor CreateEditor(ISmartContentEditorSite editorSite)
        {
            return new EditSetting<CodeEditor>();
        }

        private static string GenerateHtml(ISmartContent content)
        {
            IProperties properties = content.Properties;

            string formattedCode = properties.Code().FormattedCode();

            string figCaption = string.Empty;

            if (!string.IsNullOrEmpty(properties.Caption()))
            {
                figCaption = string.Format(CultureInfo.InvariantCulture, "<figcaption>{0}</figcaption>{1}", content.Properties.Caption(), Environment.NewLine);
            }

            string html = string.Format(CultureInfo.InvariantCulture, "{0}<figure>{0}{1}<pre><code class=\"language-{2}\">{0}{3}{0}</code></pre>{0}</figure>{0}", Environment.NewLine, figCaption, properties.Language(), formattedCode);

            return html;
        }
    }
}